package com.studerb.events.listener;

import static com.studerb.util.Constants.EVENT_SERVICE_NAME;

import org.apache.log4j.Logger;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventSubscriber;

import com.studerb.events.ConnectionPoolEvent.EventType;
import com.studerb.nntp.NntpConnection;
import com.studerb.view.connectionPool.ConnectionPoolTableModel;

/**
 * @author studerb
 * Listens for {@link com.studerb.events.ConnectionPoolEvent ConnectionPoolEvents}
 * and updates the main ConnectionPool Table View
 * @see com.studerb.view.connectionPool.ConnectionPoolTableModel
 * @see com.studerb.events.ConnectionPoolEvent
 *
 */
public class ConnectionPoolTableEL {
    private final Logger logger = Logger.getLogger(ConnectionPoolTableEL.class);
    private final ConnectionPoolTableModel tableModel;

    public ConnectionPoolTableEL(ConnectionPoolTableModel tableModel) {
        this.tableModel = tableModel;
        AnnotationProcessor.process(this);
    }

    @EventSubscriber(eventServiceName = EVENT_SERVICE_NAME) public void onEvent(
                    com.studerb.events.ConnectionPoolEvent evt) {
        NntpConnection connection = evt.getConnection();
        EventType eventType = evt.getType();
        switch(eventType){
            case CREATED:
                logger.debug("Connection: " + connection + " added to pool");
                tableModel.addConnection(connection);
                break;
            case DESTROYED:
                logger.debug("Connection: " + connection + " removed from pool");
                tableModel.removeConnection(connection);
                break;
            default:
                break;
        }
    }
}
